

package com.zhanghuan.scheduler.job.utils;

import com.zhanghuan.scheduler.job.dao.ScheduleJobLogDao;
import com.zhanghuan.scheduler.job.entity.ScheduleJobEntity;
import com.zhanghuan.scheduler.job.entity.ScheduleJobLogEntity;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.util.Date;


/**
 * 定时任务
 *
 */
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void executeInternal(JobExecutionContext context) {
        ScheduleJobEntity scheduleJob = (ScheduleJobEntity) context.getMergedJobDataMap()
        		.get(ScheduleJobEntity.JOB_PARAM_KEY);

        ScheduleJobLogDao scheduleJobLogDao = BaseHolder.getBean("scheduleJobLogDao");
        
        //任务开始时间
        long startTime = System.currentTimeMillis();

		ScheduleJobLogEntity scheduleJobLogEntity = new ScheduleJobLogEntity();
		scheduleJobLogEntity.setJobId(scheduleJob.getJobId());
		scheduleJobLogEntity.setBeanName(scheduleJob.getBeanName());
		scheduleJobLogEntity.setParams(scheduleJob.getParams());
		scheduleJobLogEntity.setCreateTime(new Date());
        
        try {
            //执行任务
        	logger.debug("任务准备执行，任务ID：" + scheduleJob.getJobId());

			Object target = BaseHolder.getBean(scheduleJob.getBeanName());
			Method method = target.getClass().getDeclaredMethod("run", String.class);
			method.invoke(target, scheduleJob.getParams());

			long times = System.currentTimeMillis()-startTime;
			scheduleJobLogEntity.setTimes((int)times);
			//失败：1 成功：0
			scheduleJobLogEntity.setStatus(0);

		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
			long times = System.currentTimeMillis()-startTime;
			scheduleJobLogEntity.setTimes((int)times);
			//失败：1 成功：0
			scheduleJobLogEntity.setStatus(1);
			scheduleJobLogEntity.setError(e.toString());
		}finally {
			scheduleJobLogDao.save(scheduleJobLogEntity);
		}
    }
}
